package com.shaoshaohuo.app.ui.shipper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.CancelableCallback;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMap.OnCameraChangeListener;
import com.amap.api.maps2d.AMap.OnInfoWindowClickListener;
import com.amap.api.maps2d.AMap.OnMapClickListener;
import com.amap.api.maps2d.AMap.OnMapLoadedListener;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.Cinema;
import com.amap.api.services.poisearch.Dining;
import com.amap.api.services.poisearch.Hotel;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.amap.api.services.poisearch.Scenic;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.MyBaseAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.PoiEntity;
import com.shaoshaohuo.app.framework.Logger;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.utils.ToastUtil;
import com.shaoshaohuo.app.view.TopbarView;

import java.util.List;

//import com.amap.api.location.LocationManagerProxy;
//import com.amap.api.location.LocationProviderProxy;

public class SelectAddressMarkerActivity extends BaseActivity
                implements LocationSource, AMapLocationListener, OnCameraChangeListener, OnMapLoadedListener, OnMarkerClickListener,
                OnInfoWindowClickListener, InfoWindowAdapter, CancelableCallback, OnMapClickListener, OnPoiSearchListener {
	
	
    private TopbarView mTopbarView;
    private AMap aMap;

    private MarkerOptions markerOption;

    private Marker marker2;// 有跳动效果的marker对象

    private MapView mapView;

    private ListView mPoiListView;

    private OnLocationChangedListener mListener;

//    private LocationManagerProxy aMapManager;

    private AMapLocation aMapLocation;

    private int mWidth;

    private int mHeight;

    private double mcurrentLat = 0;

    private double mcurrentLon = 0;

    private int mSelectPosition = 0;
    private MyAdapter mAdapter;

    private TextView mSearchText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marker_me);
        initView(savedInstanceState);
       // showDialog();
        setUpView();
        initPoi();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            mWidth = mapView.getWidth();
            mHeight = mapView.getHeight();
        }
    }

    private void initView(Bundle savedInstanceState) {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
        mPoiListView = (ListView) this.findViewById(R.id.listview_address);
        aMap = mapView.getMap();
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);

        // Toast.makeText(this, "aMap.getMaxZoomLevel():"+aMap.getMaxZoomLevel(), 0).show();

        aMap.moveCamera(CameraUpdateFactory.zoomTo((float) (15.0)));

        mSearchText = (TextView) this.findViewById(R.id.textview_search);
        mSearchText.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SelectAddressMarkerActivity.this, PoiKeywordSearchActivity.class);
                startActivityForResult(intent, 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        if (arg1 == RESULT_OK) {
            setResult(RESULT_OK, arg2);
            finish();
        }
    }

    private void setUpView() {

        mTopbarView.setCenterText("选择地址");
        mTopbarView.setLeftView(true, true);
        mTopbarView.setRightText("确定");
        mTopbarView.setRightClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (poiItems == null || poiItems.isEmpty()) {
                    showToast("请选择地址");
                } else {
                    PoiItem poiItem = poiItems.get(mSelectPosition);
                    PoiEntity poi = new PoiEntity();
                    poi.setAddress(poiItem.getSnippet());
                    poi.setId(poiItem.getCityCode());
                    poi.setCityname(poiItem.getCityName());
                    poi.setLat(poiItem.getLatLonPoint().getLatitude());
                    poi.setLng(poiItem.getLatLonPoint().getLongitude());
                    poi.setTitle(poiItem.getTitle());

                    Intent intent = new Intent();
                    intent.putExtra(ExtraName.poi, poi);
                    setResult(RESULT_OK, intent);
                    finish();
                }

            }
        });

        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true); // 是否显示默认的定位按钮
        aMap.setMyLocationEnabled(true);
        // aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        addMarkersToMap();// 往地图上添加marker'

        mPoiListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                mSelectPosition = arg2;
                mAdapter.notifyDataSetChanged();
            }
        });
    }
 
    private void addMarkersToMap() {
         CameraPosition cameraPosition = aMap.getCameraPosition();
         markerOption = new MarkerOptions();
//         markerOption.title("测试标题").snippet("测试内容");
         markerOption.draggable(true);
         markerOption.position(cameraPosition.target);
         // markerOption.icon(BitmapDescriptorFactory
         // .fromResource(R.drawable.arrow));
         marker2 = aMap.addMarker(markerOption);
         // marker旋转90度
         // marker2.setRotateAngle(90);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
//        if (aMapManager == null) {
//            aMapManager = LocationManagerProxy.getInstance(this);
//            /*
//             * mAMapLocManager.setGpsEnable(false);//
//             * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true
//             */
//            // Location API定位采用GPS和网络混合定位方式，时间最短是2000毫秒
//            aMapManager.requestLocationData(LocationProviderProxy.AMapNetwork, -1, 10, this);
//        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
//        mListener = null;
//        if (aMapManager != null) {
//            aMapManager.removeUpdates(this);
//            aMapManager.destroy();
//        }
//        aMapManager = null;
    }

    /**
     * marker点击时跳动一下
     */
    public void jumpPoint(final Marker marker) {
        // final Handler handler = new Handler();
        // final long start = SystemClock.uptimeMillis();
        //// Projection proj = aMap.getProjection();
        //// Point startPoint = proj.toScreenLocation(marker.getPosition());
        //// startPoint.offset(0, 0);
        //// final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        // final LatLng startLatLng = marker.getPosition();
        // final long duration = 1500;
        // final Interpolator interpolator = new BounceInterpolator();
        // handler.post(new Runnable() {
        //
        // @Override
        // public void run() {
        // long elapsed = SystemClock.uptimeMillis() - start;
        // float t = interpolator.getInterpolation((float) elapsed / duration);
        // double lng = t * marker.getPosition().longitude + (1 - t) * startLatLng.longitude;
        // double lat = t * marker.getPosition().latitude + (1 - t) * startLatLng.latitude;
        // marker.setPosition(new LatLng(lat, lng));
        // aMap.invalidate();// 刷新地图
        // if (t < 1.0) {
        // handler.postDelayed(this, 16);
        // }
        // }
        // });
    }


    @Override
    public void onLocationChanged(AMapLocation location) {
        if (mListener != null) {
            mListener.onLocationChanged(location);// 显示系统小蓝点
//            doSearchQuery();
            // changeCamera(
            // CameraUpdateFactory.newCameraPosition(new CameraPosition(
            // new LatLng(location.getLatitude(), location.getLongitude()), 18, 30, 0)), this);
        }
        // if (location != null) {
        // this.aMapLocation = location;// 判断超时机制
        // Double geoLat = location.getLatitude();
        // Double geoLng = location.getLongitude();
        // String cityCode = "";
        // String desc = "";
        // Bundle locBundle = location.getExtras();
        // if (locBundle != null) {
        // cityCode = locBundle.getString("citycode");
        // desc = locBundle.getString("desc");
        // }
        // String str = ("定位成功:(" + geoLng + "," + geoLat + ")" + "\n精 度 :" + location.getAccuracy()
        // + "米" + "\n定位方式:" + location.getProvider()
        // + "\n定位时间:" + AMapUtil.convertToTime(location.getTime()) + "\n城市编码:" + cityCode +
        // "\n位置描述:" + desc + "\n省:"
        // + location.getProvince() + "\n市:" + location.getCity() + "\n区(县):" +
        // location.getDistrict() + "\n区域编码:"
        // + location.getAdCode());
        // ToastUtil.toast( str);
        // // myLocation.setText(str);
        // }
    }

    // /**
    // * 根据动画按钮状态，调用函数animateCamera或moveCamera来改变可视区域
    // */
    // private void changeCamera(CameraUpdate update, CancelableCallback callback) {
    // boolean animated = ((CompoundButton) findViewById(R.id.animate)).isChecked();
    // if (animated) {
    // aMap.animateCamera(update, 1000, callback);
    // } else {
    // aMap.moveCamera(update);
    // }
    // }

    // --------------------setOnCameraChangeListener------------------------
    @Override
    public void onCameraChange(CameraPosition arg0) {
        marker2.setPositionByPixels(mWidth / 2, mHeight / 2);
        // marker2.setPosition(marker2.getPosition());
        marker2.hideInfoWindow();
        // CameraPosition cameraPosition = aMap.getCameraPosition();
        // marker2.setPosition(cameraPosition.target);
    }

    @Override
    public void onCameraChangeFinish(CameraPosition arg0) {
        // marker2.showInfoWindow();
        jumpPoint(marker2);
        // marker2.getTitle();
        // marker2.setSnippet("呵呵：" + marker2.getPosition().latitude + "-" +
        // marker2.getPosition().longitude);
        Logger.e("YSL", "mcurrentLat:" + mcurrentLat + "---mcurrentLon:" + mcurrentLon + "---arg0.target.latitude:" + arg0.target.latitude
                        + "---arg0.target.longitude:" + arg0.target.longitude);
        if (mcurrentLat != arg0.target.latitude || mcurrentLon != arg0.target.longitude) {
            mcurrentLat = arg0.target.latitude;
            mcurrentLon = arg0.target.longitude;
            // Toast.makeText(this, "onCameraChangeFinish", 0).show();
            doSearchQuery();
            jumpPoint(marker2);
        }
    }

    // -----------------------setOnMapLoadedListener----------------------
    /**
     * 监听amap地图加载成功事件回调
     */
    @Override
    public void onMapLoaded() {
    }

    // -----------------------setOnMarkerClickListener----------------------
    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.equals(marker2)) {
            if (aMap != null) {
                jumpPoint(marker);
            }
        }
        // markerText.setText("你点击的是" + marker.getTitle());
        return false;
    }

    // -----------------------setOnInfoWindowClickListener----------------------
    @Override
    public void onInfoWindowClick(Marker marker) {
        // ToastUtil.toast( "你点击了infoWindow窗口" + marker.getTitle());
    }

    // -----------------------setInfoWindowAdapter----------------------
    @Override
    public View getInfoContents(Marker marker) {
        // View infoContent = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
        // render(marker, infoContent);
        // return infoContent;
        return null;
    }

    /**
     * 监听自定义infowindow窗口的infowindow事件回调
     */
    @Override
    public View getInfoWindow(Marker marker) {
        // View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);
        // render(marker, infoWindow);
        // return infoWindow;
        return null;
    }

    public void render(Marker marker, View view) {
        // if (radioOption.getCheckedRadioButtonId() == R.id.custom_info_contents) {
        // ((ImageView) view.findViewById(R.id.badge)).setImageResource(R.drawable.badge_sa);
        // } else if (radioOption.getCheckedRadioButtonId() == R.id.custom_info_window) {
        // ImageView imageView = (ImageView) view.findViewById(R.id.badge);
        // imageView.setImageResource(R.drawable.badge_wa);
        // }
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        if (title != null) {
            SpannableString titleText = new SpannableString(title);
            // titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
            titleUi.setTextSize(16);
            titleUi.setText(titleText);
        } else {
            titleUi.setText("");
        }
        String snippet = marker.getSnippet();
        TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
        if (snippet != null) {
            SpannableString snippetText = new SpannableString(snippet);
            // snippetText.setSpan(new ForegroundColorSpan(Color.GREEN), 0, snippetText.length(),
            // 0);
            snippetUi.setTextSize(14);
            snippetUi.setText(snippetText);
        } else {
            snippetUi.setText("");
        }
    }

    // -----------------------aActivity----------------------
    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    // ----------------------------CancelableCallback----------------------
    @Override
    public void onCancel() {
    }

    @Override
    public void onFinish() {
    }

    private PoiResult poiResult; // poi返回的结果

    private int currentPage = 0;// 当前页面，从0开始计数

    private PoiSearch.Query query;// Poi查询条件类

    private Marker locationMarker; // 选择的点

    private PoiSearch poiSearch;

    private PoiOverlay poiOverlay;// poi图层

    private List<PoiItem> poiItems;// poi数据

    private Marker detailMarker;// 显示Marker的详情

    /**
     * 初始化AMap对象
     */
    private void initPoi() {
        setUpMapPoi();
        setSelectType();
        // Button locationButton = (Button) findViewById(R.id.locationButton);
        // locationButton.setOnClickListener(this);
        // Button searchButton = (Button) findViewById(R.id.searchButton);
        // searchButton.setOnClickListener(this);
        // CameraPosition cameraPosition = aMap.getCameraPosition();
        // LatLng target = cameraPosition.target;
        // locationMarker = aMap.addMarker(new MarkerOptions()
        // .anchor(0.5f, 1)
        // .icon(BitmapDescriptorFactory
        // .fromResource(R.drawable.point))
        // .position(new LatLng(target.latitude, target.longitude))
        // .title("西单为中心点，查其周边"));
        // locationMarker.showInfoWindow();
    }

    /**
     * 设置城市选择
     */
    private void setUpMapPoi() {
        aMap.setOnMarkerClickListener(this);// 添加点击marker监听事件
        aMap.setInfoWindowAdapter(this);// 添加显示infowindow监听事件
    }

    /**
     * 设置选择类型
     */
    private void setSelectType() {
        aMap.setOnMarkerClickListener(this);// 添加点击marker监听事件
        aMap.setInfoWindowAdapter(this);// 添加显示infowindow监听事件
    }

    /**
     * 注册监听
     */
    private void registerListener() {
        aMap.setOnMapClickListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
        aMap.setOnMapClickListener(null);// 进行poi搜索时清除掉地图点击事件
        currentPage = 0;
      //  query = new PoiSearch.Query("", "地名地址信息|商务住宅|公司企业", "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
       
        query = new PoiSearch.Query("", "地名地址信息|商务住宅|公司企业", "");
        query.setPageSize(50);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        query.setLimitDiscount(false);
        query.setLimitGroupbuy(false);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        // poiSearch.setBound(new SearchBound(lp, 2000, true));//
        CameraPosition cameraPosition = aMap.getCameraPosition();
        LatLng target = cameraPosition.target;
        LatLonPoint po = new LatLonPoint(target.latitude, target.longitude);
        poiSearch.setBound(new SearchBound(po, 1000));//
        // 设置搜索区域为以lp点为圆心，其周围2000米范围
        /*
         * List<LatLonPoint> list = new ArrayList<LatLonPoint>(); list.add(lp);
         * list.add(AMapUtil.convertToLatLonPoint(Constants.BEIJING)); poiSearch.setBound(new
         * SearchBound(list));// 设置多边形poi搜索范围
         */
        poiSearch.searchPOIAsyn();// 异步搜索
    }

    /**
     * 点击下一页poi搜索
     */
    public void nextSearch() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;
                query.setPageNum(currentPage);// 设置查后一页
                poiSearch.searchPOIAsyn();
            } else {
                ToastUtil.toast("无搜索结果");
            }
        }
    }

    /**
     * 查单个poi详情
     * 
     * @param poiId
     */
    public void doSearchPoiDetail(String poiId) {
        if (poiSearch != null && poiId != null) {
            poiSearch.searchPOIDetailAsyn(poiId);
        }
    }

    // @Override
    // public boolean onMarkerClick(Marker marker) {
    // if (poiOverlay != null && poiItems != null && poiItems.size() > 0) {
    // detailMarker = marker;
    // doSearchPoiDetail(poiItems.get(poiOverlay.getPoiIndex(marker))
    // .getPoiId());
    // }
    // return false;
    // }
    //
    // @Override
    // public View getInfoContents(Marker marker) {
    // return null;
    // }
    //
    // @Override
    // public View getInfoWindow(Marker marker) {
    // return null;
    // }
    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:" + cities.get(i).getCityCode() + "城市编码:" + cities.get(i).getAdCode() + "\n";
        }
//        ToastUtil.toast(infomation);
    }

    // @Override
    // public void onItemSelected(AdapterView<?> parent, View view, int position,
    // long id) {
    // if (parent == selectDeep) {
    // deepType = itemDeep[position];
    //
    // } else if (parent == selectType) {
    // tsearchType = position;
    // }
    // nextButton.setClickable(false);// 改变搜索条件，需重新搜索
    // }
    //
    // @Override
    // public void onNothingSelected(AdapterView<?> parent) {
    // if (parent == selectDeep) {
    // deepType = "酒店";
    // } else if (parent == selectType) {
    // tsearchType = 0;
    // }
    // nextButton.setClickable(false);// 改变搜索条件，需重新搜索
    // }
    /**
     * POI详情回调
     */
    @Override
    public void onPoiItemDetailSearched(PoiItemDetail result, int rCode) {
        if (rCode == 0) {
            if (result != null) {// 搜索poi的结果
                if (detailMarker != null) {
                    StringBuffer sb = new StringBuffer(result.getSnippet());
                    if ((result.getGroupbuys() != null && result.getGroupbuys().size() > 0)
                                    || (result.getDiscounts() != null && result.getDiscounts().size() > 0)) {
                        if (result.getGroupbuys() != null && result.getGroupbuys().size() > 0) {// 取第一条团购信息
                            sb.append("\n团购：" + result.getGroupbuys().get(0).getDetail());
                        }
                        if (result.getDiscounts() != null && result.getDiscounts().size() > 0) {// 取第一条优惠信息
                            sb.append("\n优惠：" + result.getDiscounts().get(0).getDetail());
                        }
                    } else {
                        sb = new StringBuffer("地址：" + result.getSnippet() + "\n电话：" + result.getTel() + "\n类型：" + result.getTypeDes());
                    }
                    // 判断poi搜索是否有深度信息
                    if (result.getDeepType() != null) {
                        // 如果大家需要深度信息，可以查看下面的代码，现在界面上未显示相关代码
                        sb = getDeepInfo(result, sb);
                        detailMarker.setSnippet(sb.toString());
                    } else {
                        ToastUtil.toast("此Poi点没有深度信息");
                    }
                }
            } else {
                ToastUtil.toast(R.string.no_result);
            }
        } else if (rCode == 27) {
            ToastUtil.toast(R.string.error_network);
        } else if (rCode == 32) {
            ToastUtil.toast(R.string.error_key);
        } else {
            ToastUtil.toast(getString(R.string.error_other) + rCode);
        }
    }

    /**
     * POI深度信息获取
     */
    private StringBuffer getDeepInfo(PoiItemDetail result, StringBuffer sbuBuffer) {
        switch (result.getDeepType()) {
        // 餐饮深度信息
        case DINING:
            if (result.getDining() != null) {
                Dining dining = result.getDining();
                sbuBuffer.append("\n菜系：" + dining.getTag() + "\n特色：" + dining.getRecommend() + "\n来源：" + dining.getDeepsrc());
            }
            break;
        // 酒店深度信息
        case HOTEL:
            if (result.getHotel() != null) {
                Hotel hotel = result.getHotel();
                sbuBuffer.append("\n价位：" + hotel.getLowestPrice() + "\n卫生：" + hotel.getHealthRating() + "\n来源：" + hotel.getDeepsrc());
            }
            break;
        // 景区深度信息
        case SCENIC:
            if (result.getScenic() != null) {
                Scenic scenic = result.getScenic();
                sbuBuffer.append("\n价钱：" + scenic.getPrice() + "\n推荐：" + scenic.getRecommend() + "\n来源：" + scenic.getDeepsrc());
            }
            break;
        // 影院深度信息
        case CINEMA:
            if (result.getCinema() != null) {
                Cinema cinema = result.getCinema();
                sbuBuffer.append("\n停车：" + cinema.getParking() + "\n简介：" + cinema.getIntro() + "\n来源：" + cinema.getDeepsrc());
            }
            break;
        default:
            break;
        }
        return sbuBuffer;
    }

    /**
     * POI搜索回调方法
     */
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {

        if (mcurrentLat != result.getBound().getCenter().getLatitude() || mcurrentLon != result.getBound().getCenter().getLongitude()) {
            return;
        }
        
        
        if (rCode == 0) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        // aMap.clear();// 清理之前的图标
                        // poiOverlay = new PoiOverlay(aMap, poiItems);
                        // poiOverlay.removeFromMap();
                        // poiOverlay.addToMap();
                        // poiOverlay.zoomToSpan();

                        if (mAdapter == null) {
                            mAdapter = new MyAdapter(this, poiItems, false);
                            mPoiListView.setAdapter(mAdapter);
                        } else {
                            mSelectPosition = 0;
                            mAdapter.setData(poiItems);
                        }

                    } else if (suggestionCities != null && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);
                    } else {
                        ToastUtil.toast(R.string.no_result);
                    }
                }
            } else {
                ToastUtil.toast(R.string.no_result);
            }
        } else if (rCode == 27) {
            ToastUtil.toast(R.string.error_network);
        } else if (rCode == 32) {
            ToastUtil.toast(R.string.error_key);
        } else {
            ToastUtil.toast(getString(R.string.error_other) + rCode);
        }
    }

    @Override
    public void onMapClick(LatLng latng) {
        locationMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1).icon(BitmapDescriptorFactory.fromResource(R.drawable.point))
                        .position(latng).title("点击选择为中心点"));
        // locationMarker.showInfoWindow();
    }

    private class MyAdapter extends MyBaseAdapter<PoiItem> {

        public MyAdapter(Context ctx, List<PoiItem> list, boolean flag) {
            super(ctx, list, flag);
        }

        @Override
        public View getView(int pos, View view1, ViewGroup group) {
            View view = View.inflate(context, R.layout.view_poi_item, null);
            TextView textview = (TextView) view.findViewById(R.id.textview_name);
            TextView addressText = (TextView) view.findViewById(R.id.textview_address);
            ImageView selectImage = (ImageView) view.findViewById(R.id.imageview_select);
            PoiItem poiItem = list.get(pos);
            if (TextUtils.isEmpty(poiItem.getTitle())) {
                textview.setVisibility(View.GONE);
            } else {
                textview.setText(poiItem.getTitle());
            }

            if (TextUtils.isEmpty(poiItem.getSnippet())) {
                addressText.setVisibility(View.GONE);
            } else {
                addressText.setText(poiItem.getSnippet());
            }

            if (mSelectPosition == pos) {
                selectImage.setVisibility(View.VISIBLE);
            } else {
                selectImage.setVisibility(View.GONE);
            }

            return view;
        };
    }
}
